﻿//
//jGridControl
//
(function ($) {
    $.fn.jFormField = function (data) {
        var formField = this;

        //类型切换
        formField.find('select.type').change(function () {
            if ($(this).val() == 'text' || $(this).val() == 'long_text') {
                formField.find('dl.data').hide();
                formField.find('dl.format').show();
            }
            else {
                formField.find('dl.data').show();
                formField.find('dl.format').hide();
            }
        });
        formField.find('select.type').trigger('change');

        //删除按钮
        formField.find('a.remove').click(function () {
            var field = $(this).parent('.formfield');
            alertMsg.confirm('请确认删除此项目', { okCall: function () {
                field.remove();
            }
            })
        });
        //数据源处理
        var treeId = new Date().valueOf();
        formField.find('ul.data').attr('id', treeId).addClass('ztree');

        var nodes = [];
        try {
            nodes = $.parseJSON(data.DataSource);
        } catch (e) {
        }
        if (!nodes || nodes.length == 0) {
            nodes = [{ name: "数据源", children: [{ name: "选项1" }, { name: "选项2" }, { name: "选项3" }, { name: "选项4"}]}];

        }
        var treeObj = $.fn.zTree.init(formField.find('ul.data'), {
            view: {
                addHoverDom: function (treeId, treeNode) {
                    var sObj = $("#" + treeNode.tId + "_span");
                    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
                    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
				+ "' title='增加' onfocus='this.blur();'></span>";
                    sObj.after(addStr);
                    var btn = $("#addBtn_" + treeNode.tId);
                    if (btn) btn.bind("click", function () {
                        treeObj.addNodes(treeNode, { name: "选项" });
                        return false;
                    });
                },
                removeHoverDom: function (treeId, treeNode) {
                    $("#addBtn_" + treeNode.tId).unbind().remove();
                },
                selectedMulti: false
            },
            edit: {
                enable: true,
                removeTitle: "删除",
                renameTitle: "编辑",
                showRemoveBtn: function (treeId, treeNode) {
                    return treeNode.name != '数据源';
                },
                showRenameBtn: function showRenameBtn(treeId, treeNode) {
                    return treeNode.name != '数据源';
                }
            }
        }, nodes);

    }
})(jQuery);

function addFormField(ui, field) {
    var data = $.extend({ Id:0, FieldName: '', Sort: 999, Memo: '', ValidatorConfig: $.toJSON({ Required: 0, Format: '-1'} )}, field);
    var html = '  <div class="formfield">'+
		'<h3 class="contentTitle">项目' + (ui.find('.formfield').length + 1) + '</h3>  ' +
        '<input class="id" type="hidden" value="' + data.Id + '"/>' +
        '<dl class="nowrap title">'+
         '   <dt>标题：</dt>'+
          '  <dd>'+
        '        <input type="text"  value="' + data.FieldName + '"/>' +
         '       </dd>  '+  
        '</dl>'+
        '<dl class="nowrap type">'+
            '<dt>类型：</dt>'+
            '<dd>'+
            '<select class="type">'+
                '<option value="text">文本输入</option>'+
                '<option value="long_text">长文本输入</option>'+
                '<option value="rbox">单选框</option>'+
                '<option value="cbox">多选框</option>'+
                '<option value="ddlist">下拉框</option>'+
            '</select>'+
            '</dd>  '+
        '</dl>'+
        '<dl class="nowrap required"><dt>必填：</dt>'+
         '   <dd>'+
          '  <input type="checkbox" />'+
           '     </dd>  '+
        '</dl>'+
        '<dl class="nowrap format">'+
            '<dt>验证：</dt><dd>'+
            '<select>'+
                '<option value="-1">无</option>'+
                '<option value="digits">数字</option>'+
                '<option value="letters">字母</option>'+
                '<option value="chinese">中文汉字</option>'+
                '<option value="mobile">手机号码</option>'+
                '<option value="tel">电话</option>'+
                '<option value="email">邮箱</option>'+
                '<option value="qq">QQ</option>'+
                '<option value="date">日期</option>'+
                '<option value="postcode">邮政编码</option>'+
            '</select>'+
                '</dd>  '+
        '</dl>' +
        '<dl class="nowrap data">' +
            '<dt>&nbsp;</dt>' +
            '<dd>' +
            '<ul class="data"></ul>' +
            '</dd>  ' +
        '</dl>' +
        '<dl class="nowrap sort">'+
            '<dt>排序：</dt>'+
            '<dd>'+
                '<input type="text" value="' + data.Sort + '"/>' +
                '</dd>  '+
        '</dl>'+
        '<dl class="nowrap memo">'+
            '<dt>说明：</dt>'+
            '<dd><textarea cols="75" rows="2">' + data.Memo + '</textarea>' +
                '</dd>  '+
        '</dl>'+
        '<a class="button remove" style="float:right"><span>删除</span></a>'+
        '<div class="divider"></div>'+
        '</div>';

    ui.append(html);
    var formField = ui.find('.formfield:last');//.jFormField(data);

    formField.find('select.type').val(data.ControlType);

    var validorConfig = $.extend({ Required: 0, Format: '-1'},$.parseJSON(data.ValidatorConfig));
    formField.find('dl.required input').attr('checked', (validorConfig.Required=='1'));

    formField.find('dl.format select').val(validorConfig.Format);

    formField.jFormField(data);

    //滚到最低
    if (!field) {
        var scrollTop = ui[0].scrollHeight;
        ui.scrollTop(scrollTop);
    }

}


function getFormFieldList(ui) {
    var fieldList = [];
    ui.find('.formfield').each(function () {
        var jField = $(this);
        var field = {
            Id: jField.find('input.id').val(),
            FieldName: jField.find('dl.title input').val(),
            ControlType: jField.find('dl.type select').val(),
            ValidatorConfig: jField.find('dl.validator input').val(),
            Memo: jField.find('dl.memo textarea').val(),
            Sort: jField.find('dl.sort input').val(),
            ValidatorConfig:$.toJSON({
                Required: jField.find('dl.required input').attr('checked') ? "1" : "0",
                Format: jField.find('dl.format select').val()
            })
        }

        var treeObj = $.fn.zTree.getZTreeObj(jField.find('dl.data ul.data').attr('id'));

        field.DataSource = $.toJSON(getDataFromNodes(treeObj.getNodes()));

        fieldList.push(field);
    });

    return fieldList;
}

function getDataFromNodes(nodes) {
    var datas = [];
    $(nodes).each(function () {
        var item = {};
        item.name = this.name;
        if (this.children) {
            item.children = getDataFromNodes(this.children);
        }
        datas.push(item);
    });
    return datas;
}